//
//  RTCircleHeader.m
//  Footer
//
//  Created by leotao on 16/12/27.
//  Copyright © 2016年 leotao. All rights reserved.
//

#import "RTCircleHeader.h"
#import "AnimateCircleLayer.h"

@interface RTCircleHeader ()

@property (strong, nonatomic) AnimateCircleLayer *circleLayer;

@end

@implementation RTCircleHeader

- (void)prepare
{
    [super prepare];
    
    self.circleLayer = [AnimateCircleLayer layer];
    self.circleLayer.contentsScale = [UIScreen mainScreen].scale;
    [self.layer addSublayer:self.circleLayer];
}

- (void)placeSubviews
{
    [super placeSubviews];
    
    CGFloat width = self.bounds.size.width * 0.3;
    CGFloat height = self.bounds.size.height * 1.5;
    
    self.circleLayer.frame = CGRectMake((self.bounds.size.width - width) * 0.5, (self.bounds.size.height - height) * 0.5, width, height);
}

- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState
    
    if (state == MJRefreshStateRefreshing) {
        [self startAnimation];
    } else if (state == MJRefreshStateIdle) {
        [self removeAnimation];
    }
    
}

- (void)startAnimation
{
    [self.circleLayer removeAllAnimations];
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    anim.fromValue = @(0);
    anim.toValue = @(M_PI * 2);
    anim.duration = 0.5;
    anim.repeatCount = MAXFLOAT;
    [self.circleLayer addAnimation:anim forKey:nil];
}

- (void)removeAnimation
{
    [self.circleLayer removeAllAnimations];
}

- (void)setPullingPercent:(CGFloat)pullingPercent
{
    [super setPullingPercent:pullingPercent];
    
    self.circleLayer.progress = pullingPercent;
    [self.circleLayer setNeedsDisplay];
    
    NSLog(@"%s", __func__);
}

@end
